const express = require('express')
const path = require('path')
const cookieParser = require('cookie-parser')
const logger = require('morgan')
const swaggerUi = require('swagger-ui-express')
const swaggerJsdoc = require('swagger-jsdoc')
const { expressjwt } = require('express-jwt')

// 获取路由
const indexRouter = require('./routes/index')
const operRouter = require('./routes/oper')
const fileRouter = require('./routes/file')
const tagRouter = require('./routes/tag')
const pptRouter = require('./routes/ppt')
const roomRouter = require('./routes/room')

process.on('unhandledRejection', (reason, promise) => {
  console.log('Promise: ', promise, 'Reason: ', reason)
})

// 获取app对象
const app = express()

// 引入静态文件
app.use('/', express.static(path.join(__dirname, 'public')))
app.use('/uploads', express.static(path.join(__dirname, 'uploads')))

// 配置swagger
const options = {
  definition: {
    openapi: '3.0.0',
    info: {
      title: 'FSPACE',
      version: '1.0.0'
    },
    host: 'http://localhost:3000',
    basePath: '/docs',
    produces: ['application/json', 'application/xml'],
    schemes: ['http', 'https'],
    securityDefinitions: {
      JWT: {
        type: 'apiKey',
        in: 'header',
        name: 'Authorization',
        description: ''
      }
    }
  },
  apis: ['./routes/*.js']
}
const openapiSpecification = swaggerJsdoc(options)
app.use('/docs', swaggerUi.serve, swaggerUi.setup(openapiSpecification))


// 设置跨域，这个要放在路由前面
app.all('*', function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*')
  res.header(
    'Access-Control-Allow-Headers',
    'X-Requested-With, Content-Type, Authorization'
  )
  res.header('Content-Type', 'application/json;charset=utf-8')
  res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS')
  if (req.method.toLowerCase() === 'options') {
    res.status(200).send() // 让options尝试请求快速结束
  } else {
    next()
  }
})

app.use(logger('dev'))
app.use(express.json({limit: '10240mb'}))
app.use(express.urlencoded({ extended: false, limit: '10240mb' }))
app.use(cookieParser())
// 中间件
app.use(
  expressjwt({
    credentialsRequired: true, // 必须携带token
    secret: 'leazerfspacejwt20220503',
    requestProperty: 'auth',
    algorithms: ['HS256']
  }).unless({
    path: [
      '/api/oper/authcode',
      '/api/oper/captcha',
      '/api/oper/login',
      '/api/oper/register',
      '/api/oper/reset',
      { url: /^\/uploads\/.*/, methods: ['GET'] }
    ]
  })
)
// 如果解析token失败，则执行
app.use((err, req, res, next) => {
  if (err.name === 'UnauthorizedError') {
    // res.status(401).send("invalid token...")
    res.json({ code: require('./config/code.js').tokenErr, msg: 'token错误' })
  } else {
    next(err)
  }
})

// 配置路由
app.use('/', indexRouter)
app.use('/api/oper', operRouter)
app.use('/api/file', fileRouter)
app.use('/api/tag', tagRouter)
app.use('/api/ppt', pptRouter)
app.use('/api/room', roomRouter)

// 导出app
module.exports = app
